<template>
    <div class="upload-page flex" v-if="fileList.length > 0">
        <div class="upload-container">
            <div class="uploadTopOut">
                <div class="uploadTop flex" @click="triggerFileInput">
                    <button class="select-files-btn">+ {{ t('Upload.UploadImage') }}</button>
                </div>
            </div>
            <div class="imageFileList" ref="showImageContainerRef">
                <div class="imageFileItem flex" v-for="(item,index) in fileList" :key="index">
                    <template v-if="item.afterImageUrl">
                        <div class="showImageContainer flex">
                            <ImageComparison :beforeImage="item.beforeImageUrl" :afterImage="item.afterImageUrl" :width="imgageComparisonWidth" />
                            <p>
                                {{ t('Upload.TryBatchMode') }}
                                <span style="color: #f85521">{{ t('BatchUpload.Title') }}</span>
                            </p>
                        </div>
                        <div class="rightToolBox flex">
                            <!-- <div class="toolItem flex">
                                <label class="switch">
                                    <input type="checkbox" v-model="useTextTool" />
                                    <span class="slider"></span>
                                </label>
                                <span>启用文本删除工具</span>
                            </div>
                            <p>结果仍有水印？</p>
                            <p class="headeEdit flex">
                                <svg t="1739351723039" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="14269" width="256" height="256">
                                    <path
                                        d="M604.536246 736.222443l288.794439-282.693148-287.777557-270.999007-270.999007 283.201589z m-72.70705 71.181728L264.389275 539.455809 145.922542 660.973188l164.734856 164.734856a50.844091 50.844091 0 0 0 36.099305 14.744786h107.789474a101.688183 101.688183 0 0 0 71.181728-28.981132z m109.314796 35.082423h254.220457a50.844091 50.844091 0 0 1 0 101.688183H346.248262a152.532274 152.532274 0 0 1-107.789474-44.742801l-164.734856-164.734856a101.688183 101.688183 0 0 1 0-142.363456l457.596823-480.476663a101.688183 101.688183 0 0 1 143.380337-3.559086l287.269117 270.999007a101.688183 101.688183 0 0 1 4.067527 143.888778l-3.050646 3.050646z"
                                        fill="#f85521"
                                        p-id="14270"
                                    ></path>
                                </svg>
                                尝试手动编辑
                            </p> -->
                            <!-- <div class="downloadBox">
                                <div class="btn flex">
                                    <img src="@/assets/batchUpload/download1.png" alt="" />
                                    下载
                                </div>
                                预览 301 x 301
                            </div> -->
                            <div class="downloadBox">
                                <div class="btn flex" style="color: #fff; background-color: #f85521" @click="downloadFile(item.afterImageUrl,item.originFileName)">
                                    {{ t('Upload.Download') }}
                                    <!-- <span class="pro">PRO</span> -->
                                </div>
                                {{ t('Upload.Complete') }} {{ item.dimensions }}
                            </div>
                        </div>
                    </template>
                    <div class="loadingBox flex" v-else>
                        <div class="loader"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="upload-section flex" @click="triggerFileInput" v-else>
        <div class="upload-box flex">
            <img src="@/assets/home/upload.png" alt="" />
            <span>{{ t('Home.UploadText') }}</span>
            <!-- <p>{{ t('Home.UploadTip') }}</p> -->
        </div>
        <!-- <div class="upload-buttons">
            <button>
                <img src="@/assets/home/link.png" alt="" />
                {{ t('Home.BtnText1') }}
            </button>
            <button @click="triggerFileInput">
                <img src="@/assets/home/file.png" alt="" />
                {{ t('Home.BtnText2') }}
            </button>
        </div> -->
    </div>
    <input type="file" ref="fileInput" accept="image/*" style="display: none" @change="handleFileSelect" />
</template>
<script setup>
import { onMounted, ref, watch, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/userStore'
import { ElMessage } from 'element-plus'
import ImageComparison from '@/components/ImageComparison.vue'
import { downloadFile } from '@/utils/tools'
import { createTaskApi, createMultiTaskApi } from '@/api/payment'
import encrypt from '@/utils/encrypt.js'

const imgageComparisonWidth = ref()
const fileInput = ref()
const { t } = useI18n()
const userStore = useUserStore()
const router = useRouter()
const showImageContainerRef = ref(null)
const fileList = ref([])
const triggerFileInput = () => {
    fileInput.value.click()
}

const handleFileSelect = async event => {
    // 检查用户是否已登录
    const token = encrypt.GetLocalData('accessToken')
    if (!token) {
        ElMessage.error(t('Upload.Messages.LoginFirst'))
        router.push('/login')
        return
    }

    const selectedFiles = Array.from(event.target.files)
    for (const file of selectedFiles) {
        const dimensions = await getImageDimensions(file)
        fileList.value.push({
            file:file,
            beforeImageUrl: '',
            afterImageUrl: '',
            status: 'pending',
            originFileName: file.name,
            dimensions: `${dimensions.width}x${dimensions.height}px`
        })
    }
    const file = fileList.value[0].file;
    let fdata = new FormData()
    fdata.append('file', file);
    try {
        let res = await createTaskApi(fdata)
        if(res.code === 200){
            fileList.value[fileList.value.length - 1].beforeImageUrl = URL.createObjectURL(file)
            fileList.value[fileList.value.length - 1].afterImageUrl = res.data.downloadUrl
            fileList.value[fileList.value.length - 1].originFileName = res.data.originFileName
            ElMessage.success(t('Upload.Messages.CreateSuccess'))
        }else{
            ElMessage.error(t('Upload.Messages.CreateFailed'))
        }
    } catch (error) {
        fileList.value.splice(fileList.value.length - 1, 1)
        ElMessage.error(t('Upload.Messages.CreateFailed'))
    }
}

const getImageDimensions = file => {
    return new Promise(resolve => {
        const img = new Image()
        img.onload = () => {
            resolve({ width: img.width, height: img.height })
        }
        img.src = URL.createObjectURL(file)
    })
}

/** 创建任务 */
const createTask = async () => {
    // 检查用户是否已登录
    const token = encrypt.GetLocalData('accessToken')
    if (!token) {
        ElMessage.error(t('Upload.Messages.LoginFirst'))
        router.push('/login')
        return
    }
    
    let fdata = new FormData()
    const file = fileList.value[0].file;
    fdata.append('file', file);
    let res = await createTaskApi(fdata)
}

watch(()=>fileList.value, (newVal) => {
    nextTick(() => { 
        if(fileList.value.length > 0){
            imgageComparisonWidth.value = showImageContainerRef.value[0]?.clientWidth * 0.8 + 'px'
        }
    })
},{immediate:true})

onMounted(async () => {
    let fileData = userStore.file
    if(fileData){
        // 检查用户是否已登录
        const token = encrypt.GetLocalData('accessToken')
        if (!token) {
            ElMessage.error(t('Upload.Messages.LoginFirst'))
            router.push('/login')
            return
        }
        
        fileList.value.push({
            file:fileData.file,
            beforeImageUrl: URL.createObjectURL(fileData.file),
            afterImageUrl: '',
            status: 'pending',
            originFileName: fileData.file.name,
            dimensions: fileData.dimensions
        })
        let fdata = new FormData()
        fdata.append('file', fileData.file);
        let res = await createTaskApi(fdata)
        if(res.code === 200){
            userStore.setFile(null)
            fileList.value[fileList.value.length - 1].afterImageUrl = res.data.downloadUrl
            fileList.value[fileList.value.length - 1].originFileName = res.data.originFileName
            ElMessage.success(t('Upload.Messages.CreateSuccess'))
        }else{
            ElMessage.error(t('Upload.Messages.CreateFailed'))
        }
    }
})
</script>
<style lang="scss" scoped>
.upload-page {
    width: 100%;
    min-height: calc(100% - 2px);
    margin-top: 2px;
    color: #000;
    background-color: #fff;
    padding-bottom: 50px;
    box-sizing: border-box;

    .upload-container {
        width: 70%;
        height: 100%;
        padding: 40px 0px;
        box-sizing: border-box;

        .uploadTopOut {
            width: 100%;
            height: 250px;
            padding: 20px;
            box-sizing: border-box;
            box-shadow: 2px 2px 2px #dddddd, -2px 2px 2px #dddddd, 2px -2px 2px #dddddd, -2px -2px 2px #dddddd;
            border-radius: 8px;

            .uploadTop {
                width: 100%;
                height: 100%;
                border: 1px dashed #919191;
                border-radius: 8px;
                font-size: 18px;
                color: #000;
                gap: 20px;

                .select-files-btn {
                    background: #ff5722;
                    color: white;
                    border: none;
                    padding: 12px 30px;
                    border-radius: 4px;
                    font-size: 20px;
                    cursor: pointer;
                }

                &.drag-over {
                    background-color: rgba(255, 87, 34, 0.1);
                    border: 1px dashed #ff5722;
                }
            }
        }

        .imageFileList {
            width: 100%;
            min-height: 520px;
            margin: 30px 0;
            border-radius: 10px;

            .imageFileItem {
                width: 100%;
                min-height: 450px;
                border-radius: 10px;
                box-shadow: 2px 2px 2px #dddddd, -2px 2px 2px #dddddd, 2px -2px 2px #dddddd, -2px -2px 2px #dddddd;
                margin-bottom: 20px;

                .showImageContainer {
                    width: 80%;
                    height: auto;
                    border-right: 1px solid #d3d3d3;
                    padding: 20px;
                    box-sizing: border-box;
                    flex-direction: column;

                    p {
                        height: 30px;
                        line-height: 30px;
                        font-weight: bold;
                        cursor: pointer;
                    }
                }

                .rightToolBox {
                    width: 20%;
                    height: 100%;
                    padding: 20px;
                    box-sizing: border-box;
                    flex-direction: column;
                    justify-content: flex-start;

                    .toolItem {
                        gap: 10px;
                        font-weight: 600;
                        margin-bottom: 40px;
                    }

                    .headeEdit {
                        font-size: 20px;
                        color: #f85521;
                        font-weight: bold;
                        gap: 10px;
                        cursor: pointer;
                        padding-bottom: 4px;
                        border-bottom: 1px dashed #f85521;
                        margin: 20px 0px 60px;

                        .icon {
                            width: 20px;
                            height: 20px;
                        }
                    }

                    .downloadBox {
                        width: 100%;
                        text-align: center;
                        color: #333;
                        margin-bottom: 30px;

                        img {
                            width: 20px;
                            height: 20px;
                        }

                        .btn {
                            width: 100%;
                            height: 60px;
                            border-radius: 8px;
                            background: #bdbdbd;
                            gap: 8px;
                            font-size: 20px;
                            font-weight: bold;
                            margin-bottom: 4px;
                            cursor: pointer;

                            .pro {
                                background-color: #fff;
                                padding: 1px 8px;
                                font-size: 12px;
                                color: #013af7;
                                border-radius: 10px;
                            }
                        }
                    }
                }

                .loadingBox{
                    width: 100%;
                    height: 450px;
                    justify-content: center;
                    align-items: center;
                }
            }
        }
    }
}

.upload-section {
    position: relative;
    top: 50%;
    transform: translateY(-80%);
    width: 800px;
    height: 360px;
    border: 1px dashed #767676;
    padding: 20px;
    margin-bottom: 20px;
    margin: 0 auto;
    background: #fff;
    flex-direction: column;
    border-radius: 10px;
    justify-content: flex-start;
    margin-bottom: 40px;
    color: #000;

    .upload-box {
        background-color: #efefef;
        font-size: 24px;
        width: 100%;
        height: 100%;
        flex-direction: column;
        cursor: pointer;

        span {
            font-size: 24px;
            font-weight: 600;
        }

        p {
            margin-top: 10px;
        }

        img {
            width: 60px;
            height: 60px;
            margin-bottom: 20px;
        }
    }

    .upload-buttons {
        display: flex;
        justify-content: center;
        gap: 20px;

        button {
            margin: 0 5px;
            padding: 10px 20px;
            background-color: #f0f0f0;
            border: none;
            cursor: pointer;
            font-size: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;

            img {
                width: 20px;
                height: 20px;
            }
        }
    }
}

.switch {
    position: relative;
    display: inline-block;
    width: 36px;
    height: 20px;

    input {
        opacity: 0;
        width: 0;
        height: 0;

        &:checked + .slider {
            background-color: #ff5722;
        }

        &:checked + .slider:before {
            transform: translateX(16px);
        }
    }

    .slider {
        position: absolute;
        cursor: pointer;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #ddd;
        transition: 0.3s;
        border-radius: 20px;

        &:before {
            position: absolute;
            content: '';
            height: 16px;
            width: 16px;
            left: 2px;
            bottom: 2px;
            background-color: white;
            transition: 0.3s;
            border-radius: 50%;
        }
    }
}

.loader {
    --d: 40px;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    color: #368194;
    box-shadow: calc(1 * var(--d)) calc(0 * var(--d)) 0 0, calc(0.707 * var(--d)) calc(0.707 * var(--d)) 0 0.5px, calc(0 * var(--d)) calc(1 * var(--d)) 0 1px, calc(-0.707 * var(--d)) calc(0.707 * var(--d)) 0 1.5px, calc(-1 * var(--d)) calc(0 * var(--d)) 0 2px, calc(-0.707 * var(--d)) calc(-0.707 * var(--d)) 0 2.5px, calc(0 * var(--d)) calc(-1 * var(--d)) 0 3px;
    animation: l27 1s infinite steps(8);
    margin-right: 15px;
}
@keyframes l27 {
    100% {
        transform: rotate(1turn);
    }
}
</style>
